package com.baomidou.springboot.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springboot.entity.SysMenu;
import com.baomidou.springboot.entity.SysRole;
import com.baomidou.springboot.entity.SysUser;
import com.baomidou.springboot.service.ISysMenuService;
import com.baomidou.springboot.service.ISysUserService;

@Repository
public class UserRealm extends AuthorizingRealm {
	@Autowired
	ISysUserService sysUserService;
	@Autowired
	ISysMenuService sysMenuService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principal) {
		SysUser user = (SysUser) principal.getPrimaryPrincipal();
		List<SysMenu> menus = sysMenuService.selectMenusByUserId(user.getId());
		Set<String> url = new HashSet<String>();
		for (SysMenu m : menus) {
			url.add(m.getUrl());
		}
		url.add("user:create");
//		url.add("user:create");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(url);
		return info;
//		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
		EntityWrapper<SysUser> ew = new EntityWrapper<SysUser>();
		ew.eq("username", userName);
		SysUser user = sysUserService.selectOne(ew);
		if (user != null && password.equals(user.getPassword())) {
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,
					password, getName());
			return info;
		}
		throw new IncorrectCredentialsException("账号或密码不正确");
	}

}
